package service

import (
	"sdc/repository/db/model"

	"gorm.io/gorm"
)

type ProjectService struct {
	db *gorm.DB
}

func NewProjectService(db *gorm.DB) *ProjectService {
	return &ProjectService{db: db}
}

// CreateProject 创建项目
func (s *ProjectService) CreateProject(project *model.Project) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		// 创建项目
		if err := tx.Create(project).Error; err != nil {
			return err
		}

		// 创建用户-项目关系
		relation := &model.UserProjectRelation{
			UserID:    project.UserID,
			ProjectID: project.ID,
			Role:      1, // 1: 发起人
		}
		return tx.Create(relation).Error
	})
}

// GetProjectDetail 获取项目详情
func (s *ProjectService) GetProjectDetail(projectID uint64) (*model.Project, error) {
	project := &model.Project{}
	if err := s.db.Where("id = ?", projectID).First(project).Error; err != nil {
		return nil, err
	}
	return project, nil
}

// CheckProjectOwner 检查项目是否属于用户
func (s *ProjectService) CheckProjectOwner(projectID uint64, userID uint64) bool {
	relation := &model.UserProjectRelation{}
	if err := s.db.Where("project_id = ? AND user_id = ?", projectID, userID).First(relation).Error; err != nil {
		return false
	}
	return true
}

// UpdateProject 更新项目
func (s *ProjectService) UpdateProject(projectID uint64, title, description string, images []string) error {
	return s.db.Model(&model.Project{}).Where("id = ?", projectID).Updates(map[string]interface{}{
		"title":       title,
		"description": description,
		"images":      images,
	}).Error
}

// DeleteProject 删除项目
func (s *ProjectService) DeleteProject(projectID uint64) error {
	return s.db.Delete(&model.Project{}, projectID).Error
}

// ListProjects 项目列表
func (s *ProjectService) ListProjects(categoryID uint, status int8, keyword string, page, pageSize int) (projects []model.Project, total int64, err error) {
	offset := (page - 1) * pageSize
	query := s.db.Model(&model.Project{})

	if categoryID > 0 {
		query = query.Where("category_id = ?", categoryID)
	}
	if status >= 0 {
		query = query.Where("status = ?", status)
	}
	if keyword != "" {
		query = query.Where("title LIKE ?", "%"+keyword+"%")
	}

	err = query.Count(&total).Error
	if err != nil {
		return nil, 0, err
	}

	err = query.Preload("User").Preload("Category").
		Offset(offset).Limit(pageSize).
		Order("created_at DESC").
		Find(&projects).Error

	return projects, total, err
}

// AddProjectUpdate 添加项目动态
func (s *ProjectService) AddProjectUpdate(update *model.ProjectUpdate) error {
	return s.db.Create(update).Error
}

// ListProjectUpdates 获取项目动态
func (s *ProjectService) ListProjectUpdates(projectID uint64) ([]model.ProjectUpdate, error) {
	var updates []model.ProjectUpdate
	if err := s.db.Where("project_id = ?", projectID).Find(&updates).Error; err != nil {
		return nil, err
	}
	return updates, nil
}

// UploadDocument 上传项目材料
func (s *ProjectService) UploadDocument(document *model.ProjectDocument) error {
	return s.db.Create(document).Error
}

// ListProjectDocuments 获取项目材料
func (s *ProjectService) ListProjectDocuments(projectID uint64) ([]model.ProjectDocument, error) {
	var documents []model.ProjectDocument
	if err := s.db.Where("project_id = ?", projectID).Find(&documents).Error; err != nil {
		return nil, err
	}
	return documents, nil
}

// AddProjectDocument 添加项目材料
func (s *ProjectService) AddProjectDocument(document *model.ProjectDocument) error {
	return s.db.Create(document).Error
}

// ListAuditProjects 获取审核中的项目
func (s *ProjectService) ListAuditProjects() ([]model.Project, error) {
	var projects []model.Project
	if err := s.db.Where("status = ?", 1).Find(&projects).Error; err != nil {
		return nil, err
	}
	return projects, nil
}

// AuditProject 审核项目
func (s *ProjectService) AuditProject(projectID uint64, status int8) error {
	return s.db.Model(&model.Project{}).Where("id = ?", projectID).Updates(map[string]interface{}{
		"status": status,
	}).Error
}
